package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.ExcelUtils;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.common.utils.StringUtils;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.excel.DeviceDataExcel;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 传感器
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/device/node")
public class DeviceNodeController extends BaseController {
    @Resource
    private DeviceService devicesService;
    @Resource
    private DeviceNodeService devicesNodeService;
    @Resource
    private TerminalTemperatureService terminalTemperatureService;
    @Resource
    private PianqusService pianqusService;
    @Resource
    private ShopService shopService;
    @Resource
    private FeedService feedService;

    @Log("查询设备页面")
    @GetMapping("/{deviceId}")
    @RequiresPermissions("module:deviceNode:list")
    String deviceNode(Model model,@PathVariable("deviceId") Integer deviceId) {
        model.addAttribute("deviceId",deviceId);
        model.addAttribute("deviceShowType",0);
        Device device = devicesService.findById(deviceId);
        if(device != null){
            model.addAttribute("online_state",device.getOnlineState());
        }
        return "module/device/node/node";
    }


    @Log("查询设备页面")
    @GetMapping("/byShop/{shopId}")
    @RequiresPermissions("module:deviceNode:list")
    String deviceNodeByShop(Model model,@PathVariable("shopId") Integer shopId, Integer positionType) {
        model.addAttribute("shopId",shopId);
        model.addAttribute("deviceShowType",1);
        model.addAttribute("positionType",positionType);
        QueryWrapper<Device> qw = new QueryWrapper<>();
        qw.eq("shop_id", shopId);
        qw.last("limit 1");
        Device device = devicesService.getOne(qw);
        if(device != null){
            model.addAttribute("online_state",device.getOnlineState());
        }
        QueryWrapper<Feed> feedQueryWrapper = new QueryWrapper<>();
        feedQueryWrapper.eq("state", 1);
        List<Feed> feedList = feedService.list();
        model.addAttribute("feedList",feedList);

        List<Feed> changeFeedList = new ArrayList<>();
        QueryWrapper<Feed> cqw = new QueryWrapper<>();
        cqw.eq("state", 1);
        List<Feed> feeds = feedService.list(cqw);
        Feed feed = new Feed();
        feed.setId(-1);
        feed.setFeedName("清空");
        changeFeedList.add(feed);
        if (feeds != null && feeds.size() > 0){
            changeFeedList.addAll(feeds) ;
        }
        model.addAttribute("changeFeedList",changeFeedList);
        return "module/device/node/node";
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:deviceNode:list")
    public DataTableLayUI<DeviceNode> list(DataTableLayUI<DeviceNode> condition) {




        DataTableLayUI<DeviceNode> dt = devicesNodeService.pageSearchLayUI(condition);
        List<DeviceNode> list = dt.getData();
        for (DeviceNode node : list){
            Device device = devicesService.findById(node.getDeviceId());
            if(device!=null){
                node.setDeviceNum(device.getDeviceNum());
            }
        }
        return dt;
    }

    @Log("新增设备页面")
    @GetMapping("/charts/{id}")
    String charts(@PathVariable("id") Integer id, Model model) {
        Device device = devicesService.findById(id);
        if(device!=null){
            Map<String,Object> mapReturn = terminalTemperatureService.getChartData(id, DateUtils.getDay(),DateUtils.getDay(), null);
            model.addAttribute("charts", mapReturn);
        }
        model.addAttribute("device", device);
        return "module/device/charts";
    }


    @Log("新增设备页面")
    @PostMapping("/charts/data/{deviceId}")
    @ResponseBody
    R chartsData(@PathVariable("deviceId") Integer deviceId) {
        Map<String,Object> mapReturn = terminalTemperatureService.getChartData(deviceId, DateUtils.getDay(),DateUtils.getDay(), null);
        return R.ok(mapReturn);
    }



    @Log("新增设备页面")
    @PostMapping("/charts/dataNew")
    @ResponseBody
    R chartsDataNew(@RequestParam Map<String,Object> paramJson) {
        JSONObject jsonObject = JSONUtil.parseObj(paramJson);
        int dateType = jsonObject.containsKey("dateType") ? jsonObject.getInt("dateType") : 0;
        int deviceId = jsonObject.containsKey("deviceId") && StrUtil.isNotEmpty(jsonObject.getStr("deviceId")) ? jsonObject.getInt("deviceId") : 0;
        int shopId = jsonObject.containsKey("shopId") && StrUtil.isNotEmpty(jsonObject.getStr("shopId")) ? jsonObject.getInt("shopId") : 0;
        int deviceShowType = jsonObject.containsKey("deviceShowType") && StrUtil.isNotEmpty(jsonObject.getStr("deviceShowType")) ? jsonObject.getInt("deviceShowType") : 0;

        String searchDate = jsonObject.containsKey("searchDate") && StrUtil.isNotEmpty(jsonObject.getStr("searchDate")) ? jsonObject.getStr("searchDate") : "";
        Integer positionType = jsonObject.containsKey("positionType") && StrUtil.isNotEmpty(jsonObject.getStr("positionType")) ?    Integer.parseInt(jsonObject.getStr("positionType")) : null;
        Integer feedId = jsonObject.containsKey("feedId") && StrUtil.isNotEmpty(jsonObject.getStr("feedId")) ?    Integer.parseInt(jsonObject.getStr("feedId")) : null;
        String feedIds = jsonObject.containsKey("feedIds") && StrUtil.isNotEmpty(jsonObject.getStr("feedIds")) ?    jsonObject.getStr("feedIds") : null;
        String nodeIds = jsonObject.containsKey("nodeIds") && StrUtil.isNotEmpty(jsonObject.getStr("nodeIds")) ?    jsonObject.getStr("nodeIds") : null;

        Map<String,Object> map = new HashMap<>();
        Map<String,Object> mapReturn2 = terminalTemperatureService.getChartDataByDevice(deviceId, dateType,2,shopId,deviceShowType, searchDate, positionType, feedId,feedIds,nodeIds);
        map.put("all_data_2", mapReturn2);


        Map<String,Object> mapReturn3 = terminalTemperatureService.getChartDataByDevice(deviceId, dateType,3,shopId,deviceShowType, searchDate, positionType, feedId,feedIds,nodeIds);
        map.put("all_data_3", mapReturn3);

        return R.ok(map);
    }



    @Log("新增设备页面")
    @GetMapping("/add/{deviceId}")
    @RequiresPermissions("module:deviceNode:add")
    String add(Model model,@PathVariable("deviceId") Integer deviceId) {
        DeviceNode node = new DeviceNode();
        node.setDeviceId(deviceId);

        Device device = devicesService.getById(deviceId);
        if(device != null){
            node.setShopId(device.getShopId());
        }

        model.addAttribute("addType", 0);
        model.addAttribute("node", node);

        return "module/device/node/detail";
    }


    @Log("新增设备页面")
    @GetMapping("/addByShop/{shopId}")
    @RequiresPermissions("module:deviceNode:add")
    String addByShop(Model model,@PathVariable("shopId") Integer shopId) {
        DeviceNode node = new DeviceNode();
        node.setShopId(shopId);


        List<Device> devices = devicesService.selectListByColumn("shop_id", shopId);
        model.addAttribute("addType", 1);
        model.addAttribute("devices", devices);
        model.addAttribute("node", node);

        return "module/device/node/detail";
    }



    @Log("编辑设备页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:deviceNode:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        DeviceNode node = devicesNodeService.findById(id);
        model.addAttribute("node", node);
        return "module/device/node/detail";
    }

    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:deviceNode:add")
    public R save(@Valid DeviceNode node) {
        node.setPowerState(0);
        node.setInsIndex(0);
        if(node.getDeviceType() != 5){
            node.setIsEllipse(0);
        }

        Device device = devicesService.findById(node.getDeviceId());
        if(device != null){
            node.setShopId(device.getShopId());
        }
        node.setCurrentValue(0d);

        if (devicesNodeService.save(node)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:deviceNode:edit")
    public R update(@Valid DeviceNode node) {
        if(node.getDeviceType()!=5){
            node.setIsEllipse(0);
        }

        Device device = devicesService.findById(node.getDeviceId());
        if(device != null){
            node.setShopId(device.getShopId());
        }

        devicesNodeService.updateById(node);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:deviceNode:remove")
    public R remove( Integer id) {
        if (devicesNodeService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    @Log("查询设备节点页面")
    @GetMapping("/deviceNodeData/nodeShopData")
    @RequiresPermissions("module:deviceNode:list")
    String deviceNodeData(Model model, HttpServletRequest request) {
        UserDO userDO = getUser();
        String positionType = request.getParameter("positionType");
        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if (userDO.getRoleId() == 1 || userDO.getRoleId() == 2){

        }else if (userDO.getRoleId() == 3){// 集团管理员
            qw.eq("jituan_id", userDO.getGroupId());
        }else {
            qw.eq("id", userDO.getPianquId());
        }
        if ("2".equals(positionType)){
            DataTableLayUI<Shop> condition = new DataTableLayUI<>();
            Map<String, Object> searchParams = new HashMap<>(16);
            searchParams.put("search_eq_positionType",2);
            condition.setSearchParams(searchParams);
            condition.setPage(1);
            condition.setLimit(99999);
            DataTableLayUI<Shop> dt = shopService.getShopDeviceCountListPage(condition);
            List<Shop> list = dt.getData();
            model.addAttribute("shopLis" +
                    "t",list);
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        List<Feed> feedList = feedService.list();
        model.addAttribute("feedList",feedList);
        model.addAttribute("pianquses",pianquses);
        model.addAttribute("positionType",positionType);
        return "module/device/node/shopNodeData";
    }

    @Log("查询设备")
    @ResponseBody
    @GetMapping("/nodeData/nodeDataList")
    @RequiresPermissions("module:deviceNode:list")
    public DataTableLayUI<DeviceNode> nodeDataList(DataTableLayUI<DeviceNode> condition) {
        UserDO userDO = getUser();
        Map<String, Object> searchParams = condition.getSearchParams();
//        if (userDO.getGroupId() != null && userDO.getGroupId() > 0){
//            searchParams.put("group_id", userDO.getGroupId());
//        }
        if (userDO.getRoleId() == 1 || userDO.getRoleId() == 2){

        }else if (userDO.getRoleId() == 3){// 集团管理员
            searchParams.put("group_id", userDO.getGroupId());
        }else if (userDO.getRoleId() == 4 || userDO.getRoleId() == 17){
            searchParams.put("pianqu_id", userDO.getPianquId());
        }else {
            searchParams.put("shop_id", userDO.getShopId());
        }
        if (searchParams.get("shopIds") != null && StrUtil.isNotEmpty(searchParams.get("shopIds").toString())){
            String[] shopIds = searchParams.get("shopIds").toString().split(",");
            if (shopIds != null && shopIds.length > 0){
                searchParams.put("shopIdArr", shopIds);
            }
        }
        Page<DeviceNode> page = devicesNodeService.getPage(condition);
        List<DeviceNode> list = devicesNodeService.getNodeDataPage(page,searchParams);
        DataTableLayUI<DeviceNode> dt = devicesNodeService.pageSearchCustom(page,list,condition);
        return dt;
    }

    @GetMapping("/nodeData/export")
    public void testExportExcel(@RequestParam("pianquId") String pianquId, @RequestParam("shopName") String shopName,
                                @RequestParam("export_date1") String exportDate1,
                                @RequestParam("export_date2") String exportDate2
                                ,@RequestParam("feedId") String feedId,
                                @RequestParam("shopType") String shopType,@RequestParam("isFire") String isFire,
                                @RequestParam("isUnqualified") String isUnqualified,
                                HttpServletResponse response){

        UserDO userDO = getUser();
        Map<String, Object> searchParams = new HashMap<>();
//        if (userDO.getGroupId() != null && userDO.getGroupId() > 0){
//            searchParams.put("group_id", userDO.getGroupId());
//        }
        if (userDO.getRoleId() == 1 || userDO.getRoleId() == 2){

        }else if (userDO.getRoleId() == 3){// 集团管理员
            searchParams.put("group_id", userDO.getGroupId());
        }else if (userDO.getRoleId() == 4 || userDO.getRoleId() == 17){
            searchParams.put("pianqu_id", userDO.getPianquId());
        }else {
            searchParams.put("shop_id", userDO.getShopId());
        }
        if(StrUtil.isNotEmpty(exportDate1)){
            searchParams.put("begin_time", exportDate1);
        }
        if(StrUtil.isNotEmpty(exportDate1)){
            searchParams.put("end_time", exportDate2);
        }else {
            searchParams.put("end_time", DateUtils.getTime(new Date()));
        }
        if(StrUtil.isNotEmpty(pianquId)){
            searchParams.put("pianquId", pianquId);
        }
        if(StrUtil.isNotEmpty(shopName)){
            searchParams.put("shopName", shopName);
        }
        if(StrUtil.isNotEmpty(feedId)){
            searchParams.put("feedId", feedId);
        }
        if(StrUtil.isNotEmpty(shopType)){
            searchParams.put("shopType", shopType);
        }
        if(StrUtil.isNotEmpty(isFire)){
            searchParams.put("isFire", isFire);
        }
        if(StrUtil.isNotEmpty(isUnqualified)){
            searchParams.put("isUnqualified", isUnqualified);
        }
        List<TerminalTemperature> list = terminalTemperatureService.getTemperatureList(searchParams);

        ExcelUtils.writeExcel(response, list, TerminalTemperature.class, System.currentTimeMillis() + "_不合格数据.xlsx");
    }

    @Log("导出制粒机平均温度")
    @GetMapping("/exportNodeData")
    public void exportDeviceData(@RequestParam Map<String,Object> paramJson, HttpServletResponse response){
        JSONObject jsonObject = JSONUtil.parseObj(paramJson);
        int deviceType = 2;
        int dateType = jsonObject.containsKey("dateType") ? jsonObject.getInt("dateType") : 0;
        int deviceId = jsonObject.containsKey("deviceId") && StrUtil.isNotEmpty(jsonObject.getStr("deviceId")) ? jsonObject.getInt("deviceId") : 0;
        int shopId = jsonObject.containsKey("shopId") && StrUtil.isNotEmpty(jsonObject.getStr("shopId")) ? jsonObject.getInt("shopId") : 0;
        int deviceShowType = jsonObject.containsKey("deviceShowType") && StrUtil.isNotEmpty(jsonObject.getStr("deviceShowType")) ? jsonObject.getInt("deviceShowType") : 0;
        String searchDate = jsonObject.containsKey("searchDate") && StrUtil.isNotEmpty(jsonObject.getStr("searchDate")) ? jsonObject.getStr("searchDate") : "";
        Integer positionType = jsonObject.containsKey("positionType") && StrUtil.isNotEmpty(jsonObject.getStr("positionType")) ?    Integer.parseInt(jsonObject.getStr("positionType")) : null;
        Integer feedId = jsonObject.containsKey("feedId") && StrUtil.isNotEmpty(jsonObject.getStr("feedId")) ?    Integer.parseInt(jsonObject.getStr("feedId")) : null;
        Map<String,Object> map = new HashMap<>();

        List<Map<Integer,String>> dataList = new ArrayList<>();
        List<String> days = new ArrayList<>();
        if (StringUtils.isNotBlank(searchDate)){
            days = DateUtils.getAllDayOfMonth(searchDate);
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            days = DateUtils.getAllDayOfMonth(sdf.format(new Date()));
        }
        Map<Integer,String> dateMap = new HashMap<>(16);
        dateMap.put(0, "设备名称");
        for (int k = 0; k < days.size(); k++) {
            dateMap.put(k + 1, days.get(k));
        }
        dateMap.put(days.size() + 1, "月平均值");
        dataList.add(dateMap);
        QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
        if(deviceShowType == 0){
            qwNode.eq("device_id", deviceId);
        }else{
            qwNode.eq("shop_id", shopId);
        }
        qwNode.eq("device_type", deviceType);
        if (positionType != null && positionType != 0){
            qwNode.eq("position_type", positionType);
        }
        List<DeviceNode> nodes = devicesNodeService.list(qwNode);
        if(CollUtil.isNotEmpty(nodes)) {
            for (int i =0; i < nodes.size(); i++) {
                DeviceNode node = nodes.get(i);
                String terminalName = node.getTerminalName();
                Map<Integer,String> valueMap = new HashMap<>(16);

                for (int j =0; j < days.size(); j++) {
                    String day = days.get(j);
                    if (j == 0){
                        valueMap.put(0, terminalName);
                    }
                    QueryWrapper<TerminalTemperature> qwTemp = new QueryWrapper<>();
                    qwTemp.select("ifnull(avg(wendu), 0) as avgWendu");
                    qwTemp.eq("device_id", node.getDeviceId());
                    qwTemp.eq("node_index", node.getNodeIndex());
                    qwTemp.eq("ins_index", node.getInsIndex());
                    qwTemp.gt("wendu", node.getMinShowValue());
//                    if (feedId != null && feedId != 0) {
//                        qwTemp.eq("feed_id", feedId);
//                    }
                    qwTemp.between("create_time", day + " 00:00:00", day + " 23:59:59");
                    List<TerminalTemperature> temperature = terminalTemperatureService.list(qwTemp);
                    BigDecimal wendu = new BigDecimal("0");
                    if (temperature != null && temperature.size() > 0){
                        wendu = temperature.get(0).getAvgWendu();
                        if (wendu != null){
                            wendu = temperature.get(0).getAvgWendu().setScale(2, RoundingMode.HALF_UP);
                        }
                    }
                    valueMap.put(j+1, wendu.toString());
                }

                QueryWrapper<TerminalTemperature> qwTempm = new QueryWrapper<>();
                qwTempm.select("ifnull(avg(wendu), 0) as avgWendu");
                qwTempm.eq("device_id", node.getDeviceId());
                qwTempm.eq("node_index", node.getNodeIndex());
                qwTempm.eq("ins_index", node.getInsIndex());
                qwTempm.gt("wendu", node.getMinShowValue());
//                    if (feedId != null && feedId != 0) {
//                        qwTemp.eq("feed_id", feedId);
//                    }
                qwTempm.between("create_time", days.get(0) + " 00:00:00", days.get(days.size() - 1) + " 23:59:59");
                List<TerminalTemperature> temperaturem = terminalTemperatureService.list(qwTempm);
                BigDecimal wendum = new BigDecimal("0");
                if (temperaturem != null && temperaturem.size() > 0){
                    wendum = temperaturem.get(0).getAvgWendu();
                    if (wendum != null){
                        wendum = temperaturem.get(0).getAvgWendu().setScale(2, RoundingMode.HALF_UP);
                    }
                }
                valueMap.put(days.size() + 1, wendum.toString());
                dataList.add(valueMap);
            }
        }
        ExcelUtils.writeExcelNoExcelColumn(response, dataList, System.currentTimeMillis() + "_设备数据.xlsx");
    }
}
